<template>
    <div class="boxContentCss">
        <el-form ref="formRef" :model="form" label-position="right" label-width="auto">
            <EdCreateCard :title=" isUpdate ? '编辑' : '添加人员'">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div class="zh_flex">
                    <el-form-item label="物业公司" class="width-50" prop="enterpriseName" :rules="$validate.validates({required:true,msg:'物业公司不能为空'})">
                        <el-input class="flex-input" v-model="form.enterpriseName" disabled></el-input>
                        <!-- <EdSelect v-model="form.enterpriseId" :selectParams="selectParamsCompany"></EdSelect> -->
                    </el-form-item>
                    <el-form-item label="所属组织" class="width-50" prop="orgId" :rules="$validate.validates({required:true,msg:'所属组织不能为空'})">
                    <!-- <el-form-item label="所属组织" class="width-50" prop="orgId"> -->
                        <EdCascader v-model="form.orgId" @input="handleCascader" :cascaderParams="selectParamsOrg"></EdCascader>
                    </el-form-item>
                    <el-form-item label="姓名" class="width-50" prop="personnelName" :rules="$validate.validates({required:true,msg:'姓名不能为空', type: 'name'})">
                        <el-input class="flex-input" maxlength="20" placeholder="请输入姓名" v-model="form.personnelName"></el-input>
                    </el-form-item>
                    <el-form-item label="用户手机号" class="width-50" prop="mobile" :rules="$validate.validates({required:true,msg:'用户手机号不能为空', type: 'mobile'})">
                        <el-input class="flex-input" placeholder="请输入手机号" v-model="form.mobile" @blur="handleBlur"></el-input>
                    </el-form-item>
                    <el-form-item label="登录账号" class="width-50" prop="loginName" :rules="$validate.validates({required:true,msg:'登录账号不能为空'})">
                        <el-input class="flex-input" placeholder="请输登录账号" v-model="form.loginName" :disabled="isUpdate"></el-input>
                    </el-form-item>
                    <el-form-item label="在职状态" class="width-50" prop="jobStatus" :rules="$validate.validates({required:true,msg:'在职状态不能为空'})">
                        <EdSelect v-model="form.jobStatus" :selectParams="selectParamsJobStatus"></EdSelect>
                    </el-form-item>
                    <el-form-item label="账号状态" class="width-50" prop="accountStatus" :rules="$validate.validates({required:true,msg:'账号状态不能为空'})">
                        <EdSelect v-model="form.accountStatus" :selectParams="selectParamsAccountStatus"></EdSelect>
                    </el-form-item>
                    <el-form-item label="管理类型" class="width-50" prop="userType" :rules="$validate.validates({required:true,msg:'管理类型不能为空'})">
                        <EdSelect v-model="form.userType" :selectParams="selectParamsUserType"></EdSelect>
                    </el-form-item>
                    <!-- <el-form-item label="岗位类型" class="width-50" prop="personnelType" :rules="$validate.validates({required:true,msg:'岗位类型不能为空'})">
                        <EdSelect v-model="form.personnelType" :selectParams="selectParamsJobType"></EdSelect>
                    </el-form-item> -->
                    <el-form-item label="所属部门" class="width-50" prop="userDepart">
                        <el-input class="flex-input" placeholder="请输入所属部门" v-model="form.userDepart"></el-input>
                    </el-form-item>
                    <el-form-item label="所属职能" class="width-50" prop="userFunction" :rules="$validate.validates({required:true,msg:'所属职能不能为空'})">
                        <!-- <EdSelect v-model="form.userFunction" :selectParams="selectParamsFunctions"></EdSelect> -->
                        <!-- <el-checkbox-group  v-model="form['userFunction']" @change="handleCheckBox"> -->
                        <el-checkbox-group  v-model="userFunction" @change="handleCheckBox">
                            <el-checkbox v-for="item in selectParamsFunctions.options" :key="item['value']" :label="item['label']"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="角色授权" class="width-100" prop="roleId">
                        <el-transfer filterable filter-placeholder="请输入关键词" ref="transferDom"
                        :render-content="renderFunc"  :titles="['待选列表', '已选列表']" :button-texts="['删除', '添加']"
                        v-model="form.roleId" :data="transferData" @change="handleChange"></el-transfer>
                    </el-form-item>
                </div>
                <el-form-item class="form_btns">
                    <el-button class="ed-button ed_black-bottom" @click="onSubmit('formRef')" :loading="disabled">确定</el-button>
                    <el-button class="ed-button ed_white_bottom" @click="$utilsSet.goBack($router)">取消</el-button>
                </el-form-item>
            </EdCreateCard>
        </el-form>
    </div>
</template>

<script>
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import EdDateTimePicker from 'src/components/EdDateTimePicker.vue'
    import WisdomUploadSingle from "src/components/WisdomUploadSingle.vue";
    import EdSelect from 'src/components/EdSelect.vue'
    import EdCascader from 'src/components/EdCascader.vue'
    import { defineComponent } from 'vue'
    import { detailMember, updateMember, memberAdd, getRoleList, getOrgList, getCompanyByVillageId } from "./api";
    import { getDictByCode } from "src/api/dictionaries";
    export default defineComponent({
        name: "companyCreate",
        components: { EdCreateCard, EdDateTimePicker, WisdomUploadSingle, EdSelect, EdCascader},
        data(){
            return{
                form:{
                    // enterpriseId: this.$store.getters.vid,
                    // enterpriseName: this.$store.getters.orgName,
                    enterpriseId: '',
                    enterpriseName: '',
                    orgId: [],
                    orgName: '',
                    personnelName: '',
                    mobile: '',
                    loginName: '',
                    jobStatus: '',
                    accountStatus: '',
                    userType: '',
                    // personnelType: '',
                    userDepart: '',
                    userFunction: [],
                    roleId: []
                },
                userFunction: [],
                pickerParams:{
                    valueFormat:"yyyy-MM-dd"
                },
                disabled:false,
                selectParamsCompany:{
                    options: [{
                        value: '1',
                        label: '公司1'
                    }, {
                        value: '2',
                        label: '公司2'
                    }],
                    placeholder:"请选择所属组织"
                },
                selectParamsOrg:{
                    options: [],
                    placeholder:"请选择所属组织",
                    props: {value: 'orgId', label: 'orgName', checkStrictly: true}
                },
                selectParamsJobStatus:{
                    options: [{
                        value: '0',
                        label: '在职'
                    }, {
                        value: '1',
                        label: '离职'
                    }],
                    placeholder:"请选择在职状态"
                },
                selectParamsAccountStatus:{
                    options: [{
                        value: '0',
                        label: '停用'
                    }, {
                        value: '1',
                        label: '启用'
                    }],
                    placeholder:"请选择账号状态",
                    // props: { value: '', label: '' }
                },
                selectParamsUserType:{
                    options: [],
                    placeholder:"请选择管理类型"
                },
                selectParamsJobType:{
                    options: [],
                    placeholder:"请选择岗位类型"
                },
                selectParamsFunctions:{
                    options: [],
                    placeholder:"请选择所属职能",
                    multiple: true
                },
                // data: generateData(),
                transferData: [],
                renderFunc: this.renderFunc1,
                isUpdate: false,
                id: []
            };
        },
        activated(){
            let params = {
                "endPage": 0,
                "export": true,
                "offset": 0,
                "page": 0,
                "pageSize": 0
            }
            if(this.$route.query.id){
                // 编辑 
                this.isUpdate = true;

            }else {
                this.isUpdate = false;
            }
            getRoleList(params).then(res => {
                this.transferData = res.data;
                res.data && res.data.forEach((item, index) => {
                    item['key'] = item['id'];
                    item['label'] = item['roleName'];
                })
            })
            
            // 管理类型
            getDictByCode('member_user_type').then(res=>{
                this.selectParamsUserType.options = res.data.items;
            })
            // 岗位类型
            getDictByCode('member_job_type').then(res=>{
                this.selectParamsJobType.options = res.data.items;
            })

            // 所属职能
            getDictByCode('member_functions_type').then(res=>{
                this.selectParamsFunctions.options = res.data.items;
            })

            // 公司赋初始值 1. 公司管理员 显示右上角 2. 物业小区管理员 type=2  展示右上角小区对应的公司
            let type = this.$store.getters.type;
            if(type == 2){
                getCompanyByVillageId().then(res=>{
                    this.form.enterpriseId = res.data.id;
                    this.form.enterpriseName = res.data.orgName;
                })
            }else{
                this.$set(this.form, 'enterpriseId', this.$store.getters.vid)
                this.$set(this.form, 'enterpriseName', this.$store.getters.orgName)
            }

            getOrgList().then((res) =>{
                let arr = [];
                arr.push(res.data)
                this.$set(this.selectParamsOrg, 'options', arr)
                if(this.isUpdate){
                    // 编辑 
                    this.detailCompany();
                }else {
                    this.form = {
                        enterpriseId: this.$store.getters.vid,
                        enterpriseName: this.$store.getters.orgName,
                        jobStatus: '0',
                        accountStatus: '1',
                        userType: '2',
                    }
                }
            })
        },
        deactivated(){
            this.form={
                // enterpriseId: this.$store.getters.vid,
                // enterpriseName: this.$store.getters.orgName,
                enterpriseId: '',
                enterpriseName: '',
                orgId: [],
                orgName: '',
                personnelName: '',
                mobile: '',
                loginName: '',
                jobStatus: '',
                accountStatus: '',
                userType: '',
                // personnelType: '',
                userDepart: '',
                userFunction: [],
                roleId: []
            }
            this.id = [];
            this.userFunction = [];
            // 清空 el-transfer 选中项
            this.$refs.transferDom.$refs.leftPanel.checked = [];
            this.$refs.transferDom.$refs.rightPanel.checked = [];
            this.disabled = false;
            this.$refs.formRef.resetFields()
        },
        methods:{
            detailCompany(){
                detailMember({id:this.$route.query.id}).then(response => {
                    if(response.code == 20000) {
                        this.selectParamsOrg.options.forEach((item, index) => {
                            if( item.orgId == response.data.orgId ){
                                // 一级
                                this.id.push(response.data.orgId);
                            }else{
                                item.children.forEach((v, i) => {
                                    if(v.orgId == response.data.orgId){
                                        this.id[0] = item['orgId']
                                        this.id[1] = v['orgId']
                                    }
                                })
                            }
                        })
                        this.userFunction = response.data.userFunction && response.data.userFunction.split(',') || [];
                        this.form = {
                            ...this.form,
                            id: response.data.id,
                            // enterpriseId: response.data.enterpriseId,
                            // enterpriseName:response.data.enterpriseName,
                            orgId: this.id.length>0&&this.id,
                            orgName:response.data.orgName,
                            personnelName:response.data.personnelName,
                            mobile:response.data.mobile,
                            loginName: response.data.loginName,
                            jobStatus:response.data.jobStatus!=null&&response.data.jobStatus.toString(),
                            accountStatus:response.data.accountStatus!=null&&response.data.accountStatus.toString(),
                            userType:response.data.userType!=null&&response.data.userType.toString()||response.data.userType,
                            // personnelType:response.data.personnelType!=null&&response.data.personnelType.toString(),
                            userDepart:response.data.userDepart,
                            userFunction:response.data.userFunction,
                            roleId:response.data.roleId && response.data.roleId,
                        };
                    }
                })
            },
            emitEchoTimeDate($event, name){
                // $event 子组件$emit传的参数 
                console.log('date--->', $event, name)
               this.form[name]=$event;
            },
            handleChange(value, direction, movedKeys) {
                this.form.roleId = value;
            },
            onSubmit(formName){
                this.$refs[formName].validate((valid) => {
                    if(valid){
                        this.disabled = true;
                        let query = this.form.copy();
                        let arr = this.isUpdate ? this.id : this.orgIdArr;
                        let name = '';
                        this.selectParamsOrg.options.forEach((item, index) => {
                            if(arr.length > 1){
                                if(item.orgId == arr[0]){
                                    item.children.forEach((v, i) => {
                                        if(v.orgId == arr[1]){
                                            name += v['orgName']
                                        }
                                    })
                                }
                            }else{
                                if(item.orgId == arr[0]){
                                    name += item['orgName']
                                }
                            }
                        })
                        query['orgId'] =  arr[arr.length-1];
                        query['orgName'] = name;
                        // return console.log('query-->', query)

                        if(this.isUpdate){
                            updateMember(query).then(response => {
                                if(response.code == 20000) {
                                    this.disabled = false;
                                    this.$message.success({
                                        message: '保存成功',
                                        center: true,
                                        duration: 2000,
                                    });
                                    // this.form.id = response.data;
                                    if(this.$route.query.type !=0){
                                        window.setTimeout(() => {
                                            this.$utilsSet.goBack(this.$router);
                                        }, 600)
                                    }
                                }else {
                                    this.disabled = false
                                }
                            }).catch(()=>{
                                this.disabled = false
                            })
                        }else{
                            memberAdd(query).then(response => {
                                if(response.code == 20000) {
                                    this.disabled = false;
                                    this.$message.success({
                                        message: '添加成功',
                                        center: true,
                                        duration: 2000,
                                    });
                                    // this.form.id = response.data;
                                    if(this.$route.query.type !=0){
                                        window.setTimeout(() => {
                                            this.$utilsSet.goBack(this.$router);
                                        }, 600)
                                    }
                                }else {
                                    this.disabled = false
                                }
                            }).catch(()=>{
                                this.disabled = false
                            })
                        }
                    }
                })
            },
            // 穿梭框数据
            getTransferData(){
                const data = [];
                for (let i = 1; i <= 5; i++) {
                    data.push({
                        key: i,
                        label: `备选项 ${ i }`,
                    });
                }
                this.transferData = data;
            },
            // 数据项渲染函数
            renderFunc1(h, option) {
                return h('span', option.label);
            },
            handleBlur(e){
                if(!this.isUpdate) this.$set(this.form, 'loginName', e.target.value);
                // this.form.loginName = e.target.value;
            },
            handleCascader(data){
                // console.log('data-->', data)
                let arr = JSON.parse(JSON.stringify(data))
                // this.form.orgId = arr[arr.length-1];
                this.orgIdArr = arr;
                this.id = arr;
            },
            handleCheckBox(val){
                // console.log('val---', val)
                this.$set(this.form, 'userFunction', val&&val.join(','))
            }
        }
    })
</script>

<style scoped lang="scss">
    :deep .el-form-item{
        .el-form-item__content{
            .el-input{
                //  input{
                    // width: 400px !important;
                    width: 60% !important;
                // }
            }
            .el-select{
                width: 60% !important;
                .el-input{
                    width: 100% !important;
                }
            }
            .el-cascader{
                width: 60% !important;
                .el-input{
                    width: 100% !important;
                }
            }

            .el-transfer{
                .el-transfer__buttons{
                    width: 20% !important;
                    text-align: center !important;
                }
                .el-transfer-panel{
                    width: 28% !important;
                    .el-transfer-panel__body{
                        height: 350px;
                        .el-transfer-panel__list.is-filterable {
                            height: 86% !important;
                            overflow-y: scroll;
                            &::-webkit-scrollbar-thumb{
                                background-color: #C1C1C1;
                                border-radius: 2px;
                            }
                            &::-webkit-scrollbar{
                                width: 10px;
                            }
                        }
                    }
                }
            }
        }
    }
    .img_center{
        display: flex;
        align-items: center;
    }
    .form_btns{
        // display: flex;
        // justify-content: flex-end;
        // margin-right: 10px;
        margin-left: 47px;
    }
</style>